<?php

namespace Wunder\Esorm\Eloquent;

class Builder
{
    use Must, MustNot, Should;

    /**
     * query criteria
     * @var array
     */
    private $query = [];

    private $flag = "must";

    public function getQuery()
    {
        return $this->query;
    }

    /**
     * Define condition mode
     * @param $type          // Filter type
     * @param string $key    // Field name
     * @param string $value  // Match value
     * @param string $flag
     * @return $this
     */
    public function where($type, $key="", $value="")
    {
        if(is_array($type)){
            $this->query[$this->flag][] = [
                "bool"=>$type
            ];
        }else{
            $this->query[$this->flag][] = [$type => [$key => $value]];
        }
        return $this;
    }

    /**
     * Define must type filter
     * @return $this
     */
    private function must()
    {
        $this->flag = "must";
        return $this;
    }

    /**
     * Define must_not type filter
     * @return $this
     */
    private function mustNot()
    {
        $this->flag = "must_not";
        return $this;
    }


    /**
     * Define should type filter
     * @return $this
     */
    private function should()
    {
        $this->flag = "should";
        return $this;
    }


    public function term(string $key, $value)
    {
        return $this->where("term", $key, $value);
    }

    public function terms(string $key, array $value)
    {
        return $this->where("terms", $key, $value);
    }

    public function match(string $key, string $value)
    {
        return $this->where("match", $key, $value);
    }

    public function matchPhrase(string $key, string $value)
    {
        return $this->where("match_phrase", $key, $value);
    }

    public function exists(string $key):array
    {
        return $this->where("exists", "field", $key);
    }

    public function range(string $key, array $value)
    {
        return $this->where("range", $key, $value);
    }

    public function ids(array $value)
    {
        return $this->where("ids", "values", $value);
    }
}
